import mysql_helper


VERSION = 1002
COST_TABLE = 'st_unit_cost'
TABLE = 'st_assemble_log'

db = mysql_helper.get_connect(db='purchase')
cursor = db.cursor()


# 获取产品计费信息
def get_unit_price(name):
    cursor.execute("select first_,last_,step from {} "
                   "where label='{}'".format(COST_TABLE, name))
    result = cursor.fetchone()
    return result[0], result[1], result[2]


def do_process(month):
    cursor.execute("select id,name,number from {} where total is NULL".format(TABLE))
    results = cursor.fetchall()
    for row in results:
        id_ = row[0]
        name = row[1]
        number = row[2]
        print('开始计算 {}'.format(name))
        first, last, step = get_unit_price(name)
        # print('first: {first}, last: {last}, step: {step}'.format(first=first, last=last, step=step))
        if number <= step:
            total = number * first
        else:
            total = first * step + (number - step) * last
        # 保留小数点后1位
        total = round(total, 1)
        print('total: {}'.format(total))
        cursor.execute("update {} set total={} where id={}"
                       .format(TABLE, total, id_))
    db.commit()
    print('计算完成')


do_process('2018-03')
